package org.i_plus.model.services;

import java.util.Date;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.hibernate.SessionFactory;
import org.i_plus.model.GiftBean;
import org.i_plus.model.Gift_RcdBean;
import org.i_plus.model.MemberBean;
import org.i_plus.model.dao.GiftDAOHibernate;
import org.i_plus.model.dao.Gift_RcdDAOHibernate;
import org.i_plus.model.dao.MemberDAOHibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@Path("/gift_RcdService")
public class Gift_RcdService {

	private Gift_RcdDAOHibernate dao = null;
	public void setGift_RcdDAO(Gift_RcdDAOHibernate dao){
		this.dao = dao;
	}
	
	@POST
    @Produces(MediaType.APPLICATION_JSON)
	public void sendGift(@QueryParam("fromacc")String fromacc,
											@QueryParam("toacc")String toacc,
											@QueryParam("giftid")int giftid,
											@QueryParam("gcount")String gcount){
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
		Gift_RcdDAOHibernate dao = (Gift_RcdDAOHibernate)context.getBean("Gift_RcdDAO");
		MemberDAOHibernate mdao = (MemberDAOHibernate)context.getBean("MemberDAO");
		GiftDAOHibernate gdao = (GiftDAOHibernate)context.getBean("GiftDAO");
    	SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    	sessionFactory.getCurrentSession().beginTransaction();
		
    	dao.insert(toacc, fromacc, new java.sql.Timestamp(new Date().getTime()), giftid, Integer.parseInt(gcount));
		MemberBean member = mdao.Select_By_Account(toacc);
		GiftBean gift = gdao.selectById(giftid);
		int pop = member.getPop();
		member.setPop(pop+(gift.getPop()*Integer.parseInt(gcount)));
    	
		sessionFactory.getCurrentSession().getTransaction().commit();
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
    @Consumes("application/json")
	public List<Gift_RcdBean> gift_Rcd(@QueryParam("fromacc")String fromacc){
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
		Gift_RcdDAOHibernate dao = (Gift_RcdDAOHibernate)context.getBean("Gift_RcdDAO");
		GiftDAOHibernate gdao = (GiftDAOHibernate)context.getBean("GiftDAO");
    	SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    	sessionFactory.getCurrentSession().beginTransaction();
		
    	List<GiftBean> gifts = gdao.selectAll();//為了關聯
    	
    	List<Gift_RcdBean> result = dao.selectByAccount(fromacc);
    	for(Gift_RcdBean temp:result){
    		temp.setGiftbean(gdao.selectById(temp.getGiftbean().getGiftid()));
    	}
    	
    	
		sessionFactory.getCurrentSession().getTransaction().commit();
		
	   	return result;
	}
	

	
}
